//
//  FPlayViewController.m
//  YiQiTingShu
//
//  Created by dllo on 15/11/6.
//  Copyright © 2015年 直到世界的尽头. All rights reserved.
//

#import "FPlayViewController.h"
#import "PublicHeader.h"
#import "WHNView.h"
#import "AFTools.h"
#import "WWTableContentModel.h"
#import "FAlbumDetail.h"
#import "WWContentTableCell.h"
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import "PlayerButton.h"
#import "UIImage+GaussianBlur.h"
#import "PlayerButton.h"
#import "Music.h"
#import "WHNPlayListViewController.h"
#import "CoreDataManager.h"
#import "PlayHistory.h"
#import "NSString+StringDate.h"
#import <MBProgressHUD.h>
#import "WHNList.h"
#import "WHNHistoryViewController.h"

#define URLString @"http://mobile.ximalaya.com/mobile/track/playpage/%@?albumId=%@&device=iPhone&trackUid=%@"
#define ListString @"http://mobile.ximalaya.com/mobile/playlist/album?albumId=%@&device=iPhone"

@interface FPlayViewController ()<UITableViewDataSource, UITableViewDelegate, WHNViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)WHNView *headerView;
@property(nonatomic, strong)FAlbumDetail *detail;
@property (nonatomic, strong)NSMutableArray *mp3Array;
@property (nonatomic, assign)NSInteger count;
@property (weak ,nonatomic) NSTimer *timer;
@property(nonatomic, strong)CoreDataManager *manager;
@property(nonatomic, strong)NSString *titleString;
@property(nonatomic, strong)NSString *picUrl;
@property(nonatomic, strong)MBProgressHUD *progressView;
@property(nonatomic, strong)UILabel *infoLabel;

@end

@implementation FPlayViewController

-(void)dealloc
{
    _timer = nil;
}

#pragma mark - 懒加载
#pragma mark 加载图
-(MBProgressHUD *)progressView
{
    if (!_progressView) {
        _progressView = [[MBProgressHUD alloc]initWithView:self.view];
        _progressView.labelText = @"加载中";
        [_progressView setMode:MBProgressHUDModeIndeterminate];
        [_progressView show:YES];
        [_progressView NightWithType:UIViewColorTypeNormal];
    }
    return _progressView;
}

-(UILabel *)infoLabel
{
    if (!_infoLabel) {
        _infoLabel = [[UILabel alloc] initWithFrame:FitRectMake(-10, -20, 50, 20)];
        _infoLabel.font = [UIFont systemFontOfSize:13 + FitFont];
        _infoLabel.textColor = [UIColor whiteColor];
        _infoLabel.text = @"到头了!!";
    }
    return _infoLabel;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, FitConstant_YorHeight(625))];
        [_tableView NightWithType:UIViewColorTypeNormal];
    }
    return _tableView;
}

#pragma mark 定时器
-(NSTimer *)timer{
    if (!_timer) {
        _timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:true];
        if ([[Music shareInstance].myPlayer status] == AVPlayerStatusReadyToPlay) {
            //NSLog(@"readyToPlay");
        }
        if ([[Music shareInstance].myPlayer status] == AVPlayerStatusUnknown) {
            //NSLog(@"unknown");
        }
    }
    return _timer;
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.timer setFireDate:[NSDate distantPast]];
    self.headerView.WHNPlayButton.selected = ![[NSUserDefaults standardUserDefaults] objectForKey:@"button"];
    
    [PlayerButton shareButton].hidden = YES;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"fy_backView"] forBarMetrics:UIBarMetricsDefault];
    [[Music shareInstance].myPlayer pause];
    if (_albumId) {
        [self initData];
    }
    else{
        [self initData1];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.headerView.WHNPlayButton.selected = ![[NSUserDefaults standardUserDefaults] objectForKey:@"button"];
    
    [PlayerButton shareButton].hidden = NO;
    
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar NightWithType:UIViewColorTypeNormal];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view NightWithType:UIViewColorTypeNormal];
    
    
    [self.view addSubview:[[UIView alloc] initWithFrame:CGRectMake(0, 0, FitConstant_XorWidth(1), FitConstant_YorHeight(1))]];
    [self.view addSubview:self.tableView];
    
    _headerView = [[WHNView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, FitConstant_YorHeight(510))];
    _headerView.delegate = self;
    _headerView.kind = WHNViewKindPictureTopList;
    [_headerView.WHNLeftButton addTarget:self action:@selector(lastSong:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.WHNRightButton addTarget:self action:@selector(nextSong:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.WHNHistoryButton addTarget:self action:@selector(historyButtonAcion) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = _headerView;
    
    [[NSUserDefaults standardUserDefaults] setObject:_trackID forKey:@"trackID"];
    [[NSUserDefaults standardUserDefaults] setObject:_trackUid forKey:@"trackUid"];
    [[NSUserDefaults standardUserDefaults] setObject:_albumId forKey:@"albumId"];
    
    _manager = [CoreDataManager shareManager];
    [self.view addSubview:self.progressView];
    
    [self getData];
}

#pragma mark - 上一曲, 下一曲
-(void)nextSong:(UIButton *)button
{
    NSInteger number = [self getListNumber];
    //NSLog(@"%ld", number);
    if (number == -1 || number + 1 == [Music shareInstance].urlArray.count) {
        [button addSubview:self.infoLabel];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.infoLabel removeFromSuperview];
    });
    }
    else{
        [[Music shareInstance] playMusicWith:[[Music shareInstance].urlArray[number + 1] playUrl64]];
//        [[NSUserDefaults standardUserDefaults] setObject:[[Music shareInstance].urlArray[number + 1] playUrl64] forKey:@"playUrl"];
        [PlayerButton shareButton].isPlay = YES;
        [[Music shareInstance].myPlayer play];
        [self.timer setFireDate:[NSDate distantPast]];
        [self coreDataAction];
        _trackID = [NSString stringWithFormat:@"%@", [[Music shareInstance].urlArray[number + 1] trackId]];
    }
    //NSLog(@"next");
}

-(void)lastSong:(UIButton *)button
{
    NSInteger number = [self getListNumber];
    //NSLog(@"%ld", number);
    if (number == -1 || number == 0) {
        [button addSubview:self.infoLabel];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.infoLabel removeFromSuperview];
        });
    }
    else{
        [[Music shareInstance] playMusicWith:[[Music shareInstance].urlArray[number + 1] playUrl64]];
//        [[NSUserDefaults standardUserDefaults] setObject:[[Music shareInstance].urlArray[number + 1] playUrl64] forKey:@"playUrl"];
        [PlayerButton shareButton].isPlay = YES;
        [[Music shareInstance].myPlayer play];
        [self.timer setFireDate:[NSDate distantPast]];
        [self coreDataAction];
        _trackID = [NSString stringWithFormat:@"%@", [[Music shareInstance].urlArray[number - 1] trackId]];
    }
    //NSLog(@"last");
}

-(NSInteger)getListNumber
{
    for (NSInteger i = 0; i < [Music shareInstance].urlArray.count; i++) {
        //NSLog(@"%@--%@", [[Music shareInstance].urlArray[i] albumId], _albumId);
        if ([[[Music shareInstance].urlArray[i] trackId] isEqual:_trackID]) {
            //NSLog(@"~~~~~%ld", i);
            return i;
        }
    }
    return -1;
}

-(void)getData
{
    //NSLog(@"~~~%@", [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/playlist/album?albumId=%@&device=iPhone", _albumId]);
    [AFTools getDataByURLString: [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/playlist/album?albumId=%@&device=iPhone", _albumId] WithDataBlock:^(id data) {
        _dataSource = [WHNList mj_objectArrayWithKeyValuesArray:[data objectForKey:@"data"]];
        [Music shareInstance].urlArray = _dataSource;
    }];
}

#pragma mark - 初始化数据(传入参数没有albumID时)
-(void)initData1
{
    _dataSource = [NSMutableArray array];
    self.mp3Array = [NSMutableArray array];
    //播放信息
    //NSLog(@"%@", [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", _trackID]);
    [AFTools getDataByURLString:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", _trackID] WithDataBlock:^(id data) {
        //设置播放歌曲
        self.title = [data objectForKey:@"title"];
        for (NSString *str in data) {
            if ([str isEqualToString:@"playUrl64"]) {
                [self.mp3Array addObject:[data objectForKey:str]];
            }
        }
        [PlayerButton shareButton].imageURL = [data objectForKey:@"coverMiddle"];
        self.titleString = [data objectForKey:@"title"];
        self.picUrl = [data objectForKey:@"coverMiddle"];
        //设置播放图片
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:FitRectMake(10, 10, 10, 10)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[data objectForKey:@"coverMiddle"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [[PlayerButton shareButton] setImage:imageView.image forState:UIControlStateNormal];
        }];
        _albumId = [data objectForKey:@"albumId"];
        //获取列表信息
        [AFTools getDataByURLString:[NSString stringWithFormat:URLString, _trackID, _albumId, _trackUid] WithDataBlock:^(id data) {
            //专辑数组
            NSArray *array = [WWTableContentModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"associationAlbumsInfo"]];
            //简介信息
            _detail = [FAlbumDetail mj_objectWithKeyValues:[data objectForKey:@"albumInfo"]];
            [_dataSource addObjectsFromArray:array];
            
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_detail.coverLarge]]];
            if (!image) {
                image = [UIImage imageNamed:@"placeholderZh"];
            }
            _headerView.WHNBackImageView.image = [UIImage blurryImage:image withBlurLevel:0.4];
            [_headerView.WHNCenterImageView sd_setImageWithURL:[NSURL URLWithString:_detail.coverLarge] placeholderImage:[UIImage imageNamed:@"placeholderZh"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            }];
            if (self.mp3Array.count) {
                [self.timer setFireDate:[NSDate distantFuture]];
                [[Music shareInstance].myPlayer pause];
                [PlayerButton shareButton].isPlay = YES;
                [[Music shareInstance] playMusicWith:self.mp3Array[0]];
//                [[NSUserDefaults standardUserDefaults] setObject:self.mp3Array[0] forKey:@"playUrl"];
                [[Music shareInstance].myPlayer play];
                [self.timer setFireDate:[NSDate distantPast]];
                [self coreDataAction];
            }
            else{
                [self.timer setFireDate:[NSDate distantFuture]];
                [[Music shareInstance].myPlayer pause];
                [PlayerButton shareButton].isPlay = YES;
                [[Music shareInstance] playMusicWith:[data objectForKey:@"playUrl32"]];
                [[Music shareInstance].myPlayer play];
                [self.timer setFireDate:[NSDate distantPast]];
            }
            [_tableView reloadData];
            [_progressView removeFromSuperview];
        }];
    }];
}
-(void)coreDataAction
{
    
    if (![_manager playHistoryString:_trackID]) {
        //创建人类对象
        PlayHistory *play = [NSEntityDescription insertNewObjectForEntityForName:@"PlayHistory" inManagedObjectContext:_manager.managedObjectContext];
        
        //给属性赋值
        play.trackID = _trackID;
        play.trackUid = _trackUid;
//        play.albumId = _albumId;
        play.title = _titleString;
        play.imageUrl = _picUrl;
        [_manager saveContext];
    }
}

-(void)initData
{
    _dataSource = [NSMutableArray array];
    self.mp3Array = [NSMutableArray array];
    //播放信息
    //NSLog(@"%@", [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", _trackID]);
    //NSLog(@"%@", [NSString stringWithFormat:URLString, _trackID, _albumId, _trackUid]);
    [AFTools getDataByURLString:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", _trackID] WithDataBlock:^(id data) {
        //设置播放歌曲
        self.title = [data objectForKey:@"title"];
        for (NSString *str in data) {
            if ([str isEqualToString:@"playUrl64"]) {
                [self.mp3Array addObject:[data objectForKey:str]];
            }
        }
        [PlayerButton shareButton].imageURL = [data objectForKey:@"coverMiddle"];
        //设置播放图片
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:FitRectMake(FitConstant_XorWidth(10), FitConstant_YorHeight(10), FitConstant_XorWidth(10), FitConstant_YorHeight(10))];
        _titleString = [data objectForKey:@"title"];
        _picUrl = [data objectForKey:@"coverLarge"];
        [[NSUserDefaults standardUserDefaults] setObject:[data objectForKey:@"coverMiddle"] forKey:@"picURL"];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[data objectForKey:@"coverMiddle"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [[PlayerButton shareButton] setImage:imageView.image forState:UIControlStateNormal];
            
        }];
        [self coreDataAction];
    }];
    //获取列表信息
    [AFTools getDataByURLString:[NSString stringWithFormat:URLString, _trackID, _albumId, _trackUid] WithDataBlock:^(id data) {
        //专辑数组
        NSArray *array = [WWTableContentModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"associationAlbumsInfo"]];
        //简介信息
        _detail = [FAlbumDetail mj_objectWithKeyValues:[data objectForKey:@"albumInfo"]];
        [_dataSource addObjectsFromArray:array];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_detail.coverLarge]]];
        if (!image) {
            image = [UIImage imageNamed:@"placeholderZh"];
        }
        _headerView.WHNBackImageView.image = [UIImage blurryImage:image withBlurLevel:0.4];
        [_headerView.WHNCenterImageView sd_setImageWithURL:[NSURL URLWithString:_detail.coverLarge] placeholderImage:[UIImage imageNamed:@"placeholderZh"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        [_headerView.WHNListButton addTarget:self action:@selector(playListAction) forControlEvents:UIControlEventTouchUpInside];
        if (self.mp3Array.count) {
            [self.timer setFireDate:[NSDate distantFuture]];
            [[Music shareInstance].myPlayer pause];
            [PlayerButton shareButton].isPlay = YES;
            [[Music shareInstance] playMusicWith:self.mp3Array[0]];
            [[Music shareInstance].myPlayer play];
            [self.timer setFireDate:[NSDate distantPast]];
            
        }
        else{
            [self.timer setFireDate:[NSDate distantFuture]];
            [[Music shareInstance].myPlayer pause];
            [PlayerButton shareButton].isPlay = YES;
            [[Music shareInstance] playMusicWith:[data objectForKey:@"playUrl32"]];
            [[Music shareInstance].myPlayer play];
            [self.timer setFireDate:[NSDate distantPast]];
        }
        [_tableView reloadData];
        [_progressView removeFromSuperview];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //可以修改为两组
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else{
        return 3;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *identifier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.text = _detail.intro;
        [cell.textLabel NightWithType:UIViewColorTypeNormal];
        [cell NightWithType:UIViewColorTypeNormal];
        return cell;
    }
    else{
        static NSString *identifier = @"idnetifier";
        WWContentTableCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[WWContentTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        if (_dataSource.count != 0) {
            cell.model = [_dataSource objectAtIndex:indexPath.row];
        }
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return FitConstant_YorHeight(120);
    }
    else {
        if (_dataSource.count != 0) {
            return 80;
        }else{
            return 0;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return FitConstant_YorHeight(40);
    }
    else{
        if (_dataSource.count != 0) {
            return 40;
        }
        else{
            return 0;
        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lable = [[UILabel alloc] initWithFrame:FitRectMake(FitConstant_XorWidth(10), 0, FitConstant_XorWidth(364), FitConstant_YorHeight(40))];
    [lable NightWithType:UIViewColorTypeNormal];
    if (section == 0) {
        lable.text = @"   简介";
    }
    else{
        if (_dataSource.count != 0) {
            lable.text = @"   相关推荐";
        }
        else{
        }
    }
    return lable;
}

#pragma mark 播放的控制
- (void)passValue:(BOOL)isPlay {
    if (isPlay) {
        [[Music shareInstance].myPlayer play];
        [self.timer setFireDate:[NSDate distantPast]];
    } else {
        [[Music shareInstance].myPlayer pause];
        [self.timer setFireDate:[NSDate distantFuture]];
    }
    [PlayerButton shareButton].isPlay = isPlay;
}
#pragma mark 播放列表点击方法
-(void)playListAction
{
    WHNPlayListViewController *listVC = [[WHNPlayListViewController alloc]init];
    listVC.albumId = _albumId;
    listVC.myBlock = ^(NSString *trackId, NSString *uid, NSString *title){
        _trackID = trackId;
        _trackUid = uid;
        self.title = title;
        [self initData];
    };
    listVC.dataSource = [Music shareInstance].urlArray;
    [self.navigationController pushViewController:listVC animated:YES];
}

#pragma mark - 进度条
-(void)updateProgress{
    CGFloat currentTime = CMTimeGetSeconds([Music shareInstance].myPlayer.currentTime);
    CGFloat allTime = CMTimeGetSeconds([Music shareInstance].myPlayer.currentItem.duration);
    _headerView.ChangeTime.text = [NSString stringWithFormat:@"%@ / %@", [NSString stringWithTimeString:[NSString stringWithFormat:@"%.2f", currentTime]], [NSString stringWithTimeString:[NSString stringWithFormat:@"%.2f", allTime]]];
    _headerView.ChangeTime.textColor = [UIColor whiteColor];
    _headerView.ChangeTime.font =  [UIFont fontWithName:@"Helvetica-Bold" size:15];
//    _headerView.LongTime.text = [NSString sst/]
    [_headerView.WHNSlider setProgress:currentTime / allTime];
}

#pragma mark - historyButtonAction
-(void)historyButtonAcion
{
    WHNHistoryViewController *vc = [[WHNHistoryViewController alloc] init];
    vc.historyKind = 1;
    vc.supVC = self;
    [self.navigationController pushViewController:vc animated:YES];
}










@end
